package com.lc.service.impl;

import com.cnpc.framework.base.entity.BaseResponse;
import com.cnpc.framework.base.service.impl.BaseServiceImpl;
import com.cnpc.framework.base.utils.HttpClient;
import com.cnpc.framework.utils.DateUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.framework.utils.StrUtil;
import com.lc.entity.LogRecord;
import com.lc.service.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 下雨不带伞 on 2020/3/20.
 */
@Service
public class LogServiceImpl extends BaseServiceImpl implements LogService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public BaseResponse addLogRecord(LogRecord logRecord) throws Exception {
        System.out.println(logRecord);
        BaseResponse response = new BaseResponse();
        try {
            logRecord.setCreateTime(DateUtil.format(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
            save(logRecord);
            response.setStatus(0);

        }catch (Exception e){
            baseDao.evict(logRecord);
            e.printStackTrace();
            response.setStatus(1);
        }
        return response;
    }

    @Override
    public BaseResponse addLogRecord(String mac, String ip,String device,String userId, String req, String context, String exc, String logType, String type) {
        BaseResponse response = new BaseResponse();
        LogRecord logRecord = new LogRecord();

        try {
            logRecord.setCreateTime(DateUtil.format(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
            logRecord.setIp(ip);
            logRecord.setMac(mac);
            logRecord.setDevice(device);
            logRecord.setUserId(userId);
            logRecord.setContext(context);
            logRecord.setType(type);
            logRecord.setLogType(logType);
            logRecord.setReq(req);
            logRecord.setExc(exc);
            save(logRecord);
            response.setStatus(0);

        }catch (Exception e){
            baseDao.evict(logRecord);
            e.printStackTrace();
            response.setStatus(1);
        }
        return response;
    }

    @Override
    public BaseResponse addRemoteLogRecord(String mac, String ip, String device,String userId, String req, String context, String exc, String logType, String type,String account,String pwd,String code,String openId,String locX ,String locY ,String location) {
        BaseResponse response = new BaseResponse();
        LogRecord logRecord = new LogRecord();

        try {
            logRecord.setCreateTime(DateUtil.format(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
            logRecord.setIp(ip);
            logRecord.setMac(mac);
            logRecord.setDevice(device);
            logRecord.setUserId(userId);
            logRecord.setContext(context);
            logRecord.setType(type);
            logRecord.setLogType(logType);
            logRecord.setReq(req);
            logRecord.setExc(exc);
            logRecord.setAccount(account);
            logRecord.setPwd(pwd);
            logRecord.setSms(code);
            logRecord.setOpenId(openId);
            logRecord.setLocX(locX);
            logRecord.setLocY(locY);
            logRecord.setLocation(location);
            save(logRecord);

            //HttpClient.restTemplatePostJson(PropertiesUtil.getValue("remoteLogUrl"),logRecord);
            response.setStatus(0);

        }catch (Exception e){

            e.printStackTrace();
            response.setStatus(1);
        }
        return response;
    }

    @Override
    public BaseResponse getLogRecordList( String token,String logType, String infoId, String startTime, String endTime, String content, String type, Integer pageNum, Integer pageSize) throws Exception {
        BaseResponse response = new BaseResponse();

        String cntsql = "select count(*) from log_record h where  1=1 ";
        String sql = "select h.*,dlt.name LOG_TYPE_TEXT,dt.name TYPE_TEX  from log_record h " +
                "  left join tbl_dict dlt on dlt.code = h.LOG_TYPE" +
                "  left join tbl_dict dt on dt.code = h.TYPE where 1=1 ";
        Map<String, Object> cntparams = new HashMap<>();

        if (StrUtil.isNotEmpty(logType)) {
            cntsql += " and h.LOG_TYPE = :logType ";
            sql += " and h.LOG_TYPE = :logType ";

            cntparams.put("logType", logType);
        }

        if (StrUtil.isNotEmpty(infoId)) {
            cntsql += " and h.INFO_ID = :infoId ";
            sql += " and h.INFO_ID = :infoId ";

            cntparams.put("infoId", infoId);
        }

        if (StrUtil.isNotEmpty(startTime)) {
            cntsql += " and h.CREATE_TIME >= :startTime ";
            sql += " and h.CREATE_TIME >= :startTime ";

            cntparams.put("startTime", startTime);
        }

        if (StrUtil.isNotEmpty(endTime)) {
            cntsql += " and h.CREATE_TIME <= :endTime ";
            sql += " and h.CREATE_TIME <= :endTime ";

            cntparams.put("endTime", endTime);
        }

        if (StrUtil.isNotEmpty(content)) {
            cntsql += " and (h.CONTEXT like :content or h.REQ like :content or h.REMARK like :content)";
            sql += " and h.CONTEXT like :content ";

            cntparams.put("content", "%" + content + "%");
        }

        if (StrUtil.isNotEmpty(type)) {
            cntsql += " and h.TYPE = :type ";
            sql += " and h.TYPE = :type ";

            cntparams.put("type", type);
        }

        sql += " order by h.CREATE_TIME DESC ";
        Long cnt = countBySql(cntsql, cntparams);

        List<Map<String, Object>> list = null;
        if (cnt > 0) {
            if (pageSize != null && pageSize > 0 && pageNum != null && pageNum > 0) {
                list = findMapBySql(sql, cntparams, pageNum, pageSize);
            } else {
                list = findMapBySql(sql, cntparams);
            }
        }


        Map<String, Object> data = new HashMap<>();
        data.put("count", cnt);
        data.put("list", list);
        response.setStatus(0);
        response.setData(data);
        return response;

    }

    public BaseResponse checkToken(String token) throws Exception{
        BaseResponse response = new BaseResponse();
        String sql = "select * from tbl_user u where u.token = :token and u.token_limit >=now() ";
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        Map<String, Object> user = getMapBySql(sql, params);
        if (user == null) {
            response.setStatus(1);
            response.setMessage("登录超时，请重新登录！");
            return response;
        }
        response.setData(user);
        response.setMessage(null);
        return response;
    }

    @Override
    public BaseResponse getLogRecord(String id) throws Exception {
        BaseResponse response = new BaseResponse();
        String sql = "select h.*,dlt.name LOG_TYPE_TEXT,dt.name TYPE_TEXT  from log_record h " +
                "  left join tbl_dict dlt on dlt.code = h.LOG_TYPE" +
                "  left join tbl_dict dt on dt.code = h.TYPE where  h.ID =:id ";
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        Map<String, Object> data = getMapBySql(sql,params);
        response.setStatus(0);
        response.setData(data);
        return response;
    }

    @Override
    public BaseResponse deleteLogRecord(String id) throws Exception {
        BaseResponse response = new BaseResponse();
        String sql = "delete from log_record h where  h.ID =:id ";
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        executeSql(sql,params);
        response.setStatus(0);
        return response;
    }


}
